<?php
/**
 * 关于生成二维码 小程序码
 * */
namespace app\common\service;
use app\admin\model\Config as configModel;
use think\Service;

class QrService
{		
	/***
	 * data参数有：savepath 保存的文件路径 ， width 保存的图片宽度 ， path 二维码跳转地址 ,name 保存的图片名称
	 * 
	 * */
	function createQr($args=[] , $data = []){
		    if(!isset($args['shop_id']) || $args['shop_id']==''){
		    	  return;
		    }
			$cs = configModel::getShopSettings($args['shop_id']); //获取店铺相关配置
	        if ($cs['xcx_appsercert'] == "" || $cs['xcx_appid']=='') {
	            return ['code'=>100,'msg'=>'appid或appsercert未配置'];
	        }
	        $savepath = isset($data['savepath']) ? $data['savepath'] : '';  //比如: order/  或 goods/ 后面的斜杠一定要有
	        $name = $data['name']. ".jpg";
	        if(!isset($data['path'])){
	        	 return ['code'=>100,'msg'=>'二维码地址path缺失'];
	        }else{
	        	 $path = $data['path'];
	        }
	        $filename = "./ewm/".$savepath . $name;
	        if (file_exists($filename)) {
	            $img = "/ewm/".$savepath . $name;
	            return ['code'=>200,'qr'=>$img];
	        }
	        $APPID     = $cs['xcx_appid'];
	        $APPSECRET = $cs['xcx_appsercert'];
	        $url       = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $APPID . "&secret=" . $APPSECRET;
	        $arr       = vget($url);
	        $rearr     = object2array(json_decode($arr));
	        $at        = $rearr['access_token'];
	        if ($at == "" || empty($at)) {
	            return ['code'=>100,'msg'=>'access_token未获取'];
	        }
 			
	        $width     = isset($data['width']) ? $data['width'] : 200;
	        $post_data = '{"path":"' . $path . '","width":' . $width . '}';
	        $url2      = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $at;
	        $back      = https_postquick($url2, $post_data);
	        header('Content-type:text/html;charset=utf-8');
	        $file    = fopen("./ewm/". $savepath . $name, "w"); //打开文件准备写入
	        $res_img = fwrite($file, $back); //写入
	        fclose($file); //关闭
	        $img = "/ewm/". $savepath . $end_pic;
	        return ['code'=>200,'qr'=>$img];
	}
}